package com.aat.dxfy.iparea;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
 * QPS 10
 * @author Administrator
 *
 */
public class TaobaoApi {

	private final static Logger log = LoggerFactory.getLogger(TaobaoApi.class);

	public static String[] getCityAndCode(String ip) {
		String[] cityS = null;
		String url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;

		CloseableHttpClient client = HttpClients.createDefault(); // HttpClientConnectionManagerWrapper.getHttpClient();
		CloseableHttpResponse resp = null;
		HttpGet get = new HttpGet(url);

		try {
			get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0");
			get.addHeader("Accept-Encoding", "gzip, deflate");
			resp = client.execute(get);

			if (resp.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = resp.getEntity();
				String res = EntityUtils.toString(entity);
				EntityUtils.consume(entity);

				JSONObject jobj = JSON.parseObject(res);
				if (jobj.getInteger("code") == 0) {
					JSONObject jobj2 = jobj.getJSONObject("data");
					String cityC = jobj2.getString("city_id");
					String cityU = jobj2.getString("city");
					// cityU = cityU.substring(0, cityU.length() );// 去掉市

					cityS = new String[] { cityC, cityU };

				}
			}

		} catch (IOException e) {
			log.error("dycm-route.IpAreaUtil.getCityAndCode() : " + e);
		} finally {
			try {
				if (get != null)
					get.releaseConnection();
				if (resp != null)
					resp.close();
				if (client != null)
					client.close();
			} catch (IOException e) {
				log.error("dycm-route.IpAreaUtil.run() : " + e);
			}
		}

		return cityS;
	}

	public static String convert(String utfstr) {
		StringBuilder sb = new StringBuilder();
		int i = -1;
		int pos = 0;
		while ((i = utfstr.indexOf("\\u", pos)) != -1) {
			sb.append(utfstr.substring(pos, i));
			if (i + 5 < utfstr.length()) {
				pos = i + 6;
				sb.append((char) Integer.parseInt(utfstr.substring(i + 2, i + 6), 16));
			}
		}
		return sb.toString();
	}

}
